﻿using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Controls;

namespace Ledict.ConditionExtract
{
    public partial class NodeTree_Case : BaseForm
    {
        //private NewIDBLL newid = new NewIDBLL();
        public string pid = "";

        private DataTable QuoteLawdt;
        private readonly QuoteLawRelBLL quoteLawRelBLL = new QuoteLawRelBLL();

        public string stiuationId = "";
        public string stiuationName = "";
        public string stiuationType = "";
        private readonly TreeDataBLL trbll = new TreeDataBLL();

        public NodeTree_Case()
        {
            InitializeComponent();
            GetData("t_Case_HeadWords");
        }

        private void QuoteLawRelAboutCase_Load(object sender, EventArgs e)
        {
            DV_QuoteLawRel.AutoGenerateColumns = false;
            DV_QuoteLawRel.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            t_Case_HeadWords.TreeView.AfterExpand += t_Case_HeadWords_AfterExpand;
            t_Case_HeadWords.TreeView.AfterSelect += t_Case_HeadWords_AfterSelect;
            checkedListBox1.DataSource = quoteLawRelBLL.GetHeadWindows();
            checkedListBox1.DisplayMember = "HWName";
            checkedListBox1.ValueMember = "HWType";

            ShowRelationLaw();
        }


        public void t_Case_HeadWords_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Case_HeadWords");
        }

        public void t_Case_HeadWords_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var pid = "";
            if (e.Node.Parent != null)
                pid = e.Node.Parent.Tag.ToString();
            QuoteLawdt = quoteLawRelBLL.QuoteLawRelAboutCaseList(e.Node.Tag.ToString(), e.Node.Text, e.Node.Name, pid, 0);
            ProvText.Text = "";

            DV_QuoteLawReldataPager1.ChangePageNumber(1);
        }

        public void GetData(string Tname)
        {
            var dt = trbll.GetTreeHeadWords("", Tname); // 第一层
            var arrayDR = dt.Select();

            foreach (var CaseTreeNodeRode in arrayDR)
            {
                var node = new TreeNode();

                node.Text = CaseTreeNodeRode["name"] + "(" + CaseTreeNodeRode["id"] + ")";
                node.Tag = CaseTreeNodeRode["id"];

                switch (Tname)
                {
                    case "t_Case_HeadWords":
                        if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0) //第二层
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        t_Case_HeadWords.TreeView.Nodes.Add(node);
                        break;
                }
            }
        }

        public void GetTreeHeadWordsChild(TreeNode parentNode, string Tname)
        {
            var dt = trbll.GetTreeHeadWords(parentNode.Tag.ToString(), Tname); // 第一层
            var arrayDR = dt.Select();

            foreach (var CaseTreeNodeRode in arrayDR)
            {
                var node = new TreeNode();

                node.Text = LdFormat.ObjectToString(CaseTreeNodeRode["name"]) + "(" + CaseTreeNodeRode["id"] + ")";
                node.Tag = CaseTreeNodeRode["id"];
                if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0) //第二层
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);
            }
        }

        /// <summary>
        ///     显示来源列表
        /// </summary>
        /// <param name="CC_ID"></param>
        private void ShowRelationLaw()
        {
            DV_QuoteLawRel.AutoGenerateColumns = false;
            DV_QuoteLawRel.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            DV_QuoteLawReldataPager1.ChangePageNumber(1);
        }

        private void DV_QuoteLawReldataPager1_PageNumberChanging(object sender, DataPagerPageIndexChangingEventArgs e)
        {
            if (stiuationId != "")
            {
                var startRowIndex = e.StartRowIndex;
                var maximumRows = e.MaximumRows;
                var endRowIndex = e.StartRowIndex + e.MaximumRows;
                if (QuoteLawdt == null)
                    QuoteLawdt = quoteLawRelBLL.QuoteLawRelAboutCaseList(stiuationId, stiuationName, stiuationType, pid,
                        1);

                DV_QuoteLawRel.DataSource = QuoteLawdt;

                if (QuoteLawdt.Rows.Count > 0)
                {
                    e.TotalCount = QuoteLawdt.Rows.Count;
                    var newdt = new DataTable();
                    newdt = QuoteLawdt.Clone();
                    var dr = QuoteLawdt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                    for (var i = 0; i < dr.Length; i++)
                    {
                        newdt.ImportRow(dr[i]);
                    }
                    var ProvContentDt = quoteLawRelBLL.QuoteLawRel_ProvContent(newdt, stiuationId);
                    DV_QuoteLawRel.DataSource = ProvContentDt;
                }
                else
                {
                    MessageBox.Show("没有查询结果！");
                    DV_QuoteLawRel.DataSource = new DataTable();
                }
            }
        }


        private void DV_QuoteLawRel_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var OLR_Law_ProvID = DV_QuoteLawRel.Rows[e.RowIndex].Cells["ProvInID"].Value.ToString();
                ProvText.Text = quoteLawRelBLL.GetProvText(OLR_Law_ProvID);
                var checkflat = Convert.ToBoolean(DV_QuoteLawRel.Rows[e.RowIndex].Cells["Column1"].Value);
                if (checkflat)
                    DV_QuoteLawRel.Rows[e.RowIndex].Cells["Column1"].Value = false;
                else
                    DV_QuoteLawRel.Rows[e.RowIndex].Cells["Column1"].Value = true;
            }
        }


        private void allSelect_Click(object sender, EventArgs e)
        {
            var ChooseWhere = GetWhere(1);
            QuoteLawdt = quoteLawRelBLL.GetAllByWhere(ChooseWhere);
            ProvText.Text = "";
            DV_QuoteLawReldataPager1.ChangePageNumber(1);
        }

        private void NotallSelect_Click(object sender, EventArgs e)
        {
            var ChooseWhere = GetWhere(0);
            QuoteLawdt = quoteLawRelBLL.GetAllByWhere(ChooseWhere);
            ProvText.Text = "";

            DV_QuoteLawReldataPager1.ChangePageNumber(1);
        }

        private string GetWhere(int isallProv)
        {
            var ChooseWhere = new StringBuilder();
            ChooseWhere.Append(" 1=1 ");
            var ChooseHWType = new StringBuilder();
            var ChooseProv = new StringBuilder();
            var isallHWType = 0;

            #region 类别

            var collection = checkedListBox1.CheckedItems;

            for (var i = 0; i < collection.Count; i++)
            {
                var dr = (DataRowView)collection[i];
                if (string.IsNullOrEmpty(dr.Row["HWType"].ToString())) //包含全部
                {
                    isallHWType = 1;
                    break;
                }
                if (ChooseHWType.ToString() != "")
                {
                    ChooseHWType.Append(",");
                }
                ChooseHWType.Append(dr.Row["HWType"]);
            }
            if (collection.Count > 0 && isallHWType == 0)
                ChooseWhere.Append(" and HWType in (" + ChooseHWType + ")");

            #endregion

            if (!string.IsNullOrEmpty(LawKeyWord.Text.Trim()))
                ChooseWhere.Append(" and CATName like '%" + LawKeyWord.Text.Trim() + "%'"); //法律名称

            ChooseWhere.Append(" and   PromuDate >='" + Convert.ToDateTime(PromuDateStart.Text).ToString("yyyy-MM-dd") +
                               "' and PromuDate <='" + Convert.ToDateTime(PromuDateEnd.Text).ToString("yyyy-MM-dd") +
                               "'"); //公布时间

            #region 条文内容

            if (!string.IsNullOrEmpty(ProvKeyWord.Text.Trim()))
            {
                var provArr = ProvKeyWord.Text.Split(',', '，', ' ', ' ');

                foreach (var item in provArr)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        if (ChooseProv.ToString() != "")
                        {
                            if (ProvAnd.Checked)
                                ChooseProv.Append(" and ");
                            else
                                ChooseProv.Append(" or ");
                        }
                        ChooseProv.Append(" ProvText like'%" + item + "%'");
                    }
                }

                ChooseWhere.Append(" and (  ");
                ChooseWhere.Append(ChooseProv);
                ChooseWhere.Append(" )");
            }

            #endregion

            if (isallProv == 0)
            {
                var quoteLawRelallProv = quoteLawRelBLL.QuoteLawRelGetProv(stiuationId);
                if (quoteLawRelallProv != "")
                    ChooseWhere.Append(" and  a.ProvInID not in (" + quoteLawRelallProv + ")");
            }
            return ChooseWhere.ToString();
        }

        private void LocateWord_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ProvText.SelectionStart = 0;
            ProvText.SelectionLength = ProvText.Text.Length;
            ProvText.SelectionBackColor = Color.White;
            MatchCollection mc;
            var r = new System.Text.RegularExpressions.Regex(SelectWord.Text.Trim()); //定义一个Regex对象实例
            mc = r.Matches(ProvText.Text);
            for (var i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
            {
                var start = mc[i].Index; //记录匹配字符的位置
                var length = (SelectWord.Text.Trim()).Length;
                ProvText.SelectionStart = start;
                ProvText.SelectionLength = length;
                ProvText.SelectionBackColor = Color.Blue;
            }
        }
    }
}